package com.bilibili.server.controller;

import com.bilibili.server.dto.Response;
import com.bilibili.server.entity.User;
import com.bilibili.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    // 获取当前用户信息
    @GetMapping("/me")
    public ResponseEntity<Response<User>> getCurrentUser() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            User user = userService.getUserInfo(username);
            if (user == null) {
                return new ResponseEntity<>(Response.error(404, "用户不存在"), HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(Response.success("获取成功", user), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 更新当前用户信息
    @PutMapping("/me")
    public ResponseEntity<Response<User>> updateCurrentUser(@RequestBody User updatedUser) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();

            User user = userService.updateUserInfo(username, updatedUser);
            if (user == null) {
                return new ResponseEntity<>(Response.error(404, "用户不存在"), HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(Response.success("更新成功", user), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}